package com.berte.data;

import javax.swing.*;
import java.util.Queue;

import static java.lang.Thread.sleep;

/*
 * 保存接收到的数据类
 * */
public class SaveData implements Runnable {
    private Queue<Byte> RecvQueue = null;
    private JTextArea RecvtextArea;
    private byte[] data = null;

    public volatile boolean running = true;
    public volatile boolean isRunning = true;

    @Override
    public void run() {
        while (true) {
            if (running) {
                isRunning = true;
                if (RecvQueue.isEmpty()) {
                    try {
                        sleep(10);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    data = new byte[RecvQueue.size()];
                    for (int i = 0; i < data.length; i++) {
                        data[i] = RecvQueue.poll();
                    }

                    String str = null;

                    try {
                        str = new String(data, "utf-8");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    synchronized (RecvtextArea) {
                        RecvtextArea.append(str);
                        RecvtextArea.setCaretPosition(RecvtextArea.getText().length());
                    }
                }
            } else {
                isRunning = false;
                try {
                    sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public Queue<Byte> getRecvQueue() {
        return RecvQueue;
    }

    public void setRecvQueue(Queue<Byte> RecvQueue) {
        this.RecvQueue = RecvQueue;
    }

    public JTextArea getRecvtextArea() {
        return RecvtextArea;
    }

    public void setRecvtextArea(JTextArea recvtextArea) {
        RecvtextArea = recvtextArea;
    }
}
